package com.cn.wkditui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;

import java.util.ArrayList;
import java.util.List;



/**
 * Created by wyd on 2016/3/15.
 */
public class MapActivity extends BaseActivity {
    private ImageView iv;
    private int type =0;

    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    private List<PoiInfo> lps = new ArrayList<PoiInfo>();

//    private LatLng currentLat = new LatLng(0, 0);
    private String currentName ="";
    MapView mMapView;
    BaiduMap mBaiduMap;
    public boolean isFirstLoc=true;
    private PoiSearch mPoiSearch;
    private ListView lv;
    protected List<PoiInfo> beans = new ArrayList<PoiInfo>();
    //	,tvlocation;
    String keyword="街道";
    private EditText et;
    private RelativeLayout rl;
    private double currentLat,currentLng;
    private String city,province;
    private Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        init();


        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("lat",
                            currentLat);
                    intent.putExtra("lng",
                            currentLng);
                    intent.putExtra("name",
                            currentName);
//                    beans.get(arg2).city;
                    intent.putExtra("city", city);
                    intent.putExtra("province", province);


                Log.e("MAP", "currentLat---------"+currentLat);
                Log.e("MAP", "currentLng---------"+currentLng);
                Log.e("MAP", "currentName---------"+currentName);
                Log.e("MAP","province---------"+province);
                Log.e("MAP", "city---------" + city);

                    setResult(201, intent);
                    MapActivity.this.finish();
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                Intent intent = new Intent();
                if(beans.get(arg2).location==null){
                    Toast.makeText(MapActivity.this, "此项不可选择", 0).show();
                }else{
                    if(type==0){

//						LatLng location = beans.get(arg2).location;
//						//				LatLng ll = new LatLng(location.getLatitude(),
//						//						location.getLongitude());
//						MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(location);
//						mBaiduMap.animateMapStatus(u);
                        //
//						currentLat = beans.get(arg2).location;
//						currentName  = beans.get(arg2).address;
                    }else{
                        rl.setVisibility(View.VISIBLE);
                        //					BitmapDescriptor bit =BitmapDescriptorFactory.fromResource(R.drawable.gpsbig);
                        //					MarkerOptions position = new MarkerOptions().icon(bit).position(beans.get(arg2).location);
                        //					mBaiduMap.addOverlay(position);
                    }

//                    LatLng ll = new LatLng(location.getLatitude(),
//                            location.getLongitude());
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom( beans.get(arg2).location, 17);
                    mBaiduMap.animateMapStatus(u);

//                    intent.putExtra("lat",
//                            beans.get(arg2).location.latitude);
//                    intent.putExtra("lng",
//                            beans.get(arg2).location.longitude);
//                    intent.putExtra("name",
//                            beans.get(arg2).address);
////                    beans.get(arg2).city;
//                    intent.putExtra("city", beans.get(arg2).city);

//                    setResult(201,intent);
//                    MapActivity.this.finish();

                }
                //				keyword = "楼房";
                //				Intent intent = new Intent();
                //				intent.putExtra("lat",
                //						beans.get(arg2).location.latitude);
                //				intent.putExtra("lng",
                //						beans.get(arg2).location.longitude);
                //				intent.putExtra("name",
                //						beans.get(arg2).address);
                //				setResult(201,intent);
                //				MapActivity.this.finish();
            }
        });
    }



    private void init() {
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        lv = (ListView)findViewById(R.id.lv);
        iv = (ImageView)findViewById(R.id.iv);
        bt = (Button) findViewById(R.id.bt);

        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)){
            child.setVisibility(View.INVISIBLE);
        }
        rl = (RelativeLayout) findViewById(R.id.rl);
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
        //		tvlocation =  (TextView) findViewById(R.id.tvlocation);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);



        iv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                MapActivity.this.finish();
            }
        });

        et = (EditText) findViewById(R.id.et);
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(TextUtils.isEmpty(s)){
                    type=0;
                    rl.setVisibility(View.VISIBLE);
                }else {
                    type=1;
                    mPoiSearch.searchInCity((new PoiCitySearchOption())
                            .city("长春")
                            .keyword(et.getText().toString())
                            .pageCapacity(30));
                    rl.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

        });

//		tvconfirm .setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(MapActivity.this,RegisterActivity.class);
//				intent.putExtra("lat",
//						currentLat.latitude);
//				intent.putExtra("lng",
//						currentLat.longitude);
//				intent.putExtra("name",
//						currentName);
//				setResult(201,intent);
//				MapActivity.this.finish();
//			}
//		});

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {

            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {
                // TODO Auto-generated method stub0000

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus arg0) {
                System.out.println("lat==="+arg0.target.latitude);
                System.out.println("lng==="+arg0.target.longitude);
                System.out.println("lng==="+arg0.bound);
                //				new LatLngBounds(arg0.target.latitude,arg0.target.longitude)
                //				LatLngBounds.Builder builder =
                //								mPoiSearch.searchInCity((new PoiCitySearchOption())
                //										.city("长春")
                //										.keyword("52")
                //										.pageCapacity(30));
                //								//				msSearch.geocode(new GeoCodeOption()
                //								//			    .city("长春")
                //								//			    .address(et.getText().toString())
                mPoiSearch.searchNearby(new PoiNearbySearchOption().location(arg0.target).pageCapacity(30).pageNum(0).keyword(keyword).radius(10000));
                GeoCoder coder = GeoCoder.newInstance();
                coder.reverseGeoCode(new ReverseGeoCodeOption().location(arg0.target));
                coder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        System.out.println(arg0.getAddress());
                        //						tvlocation	.setText(arg0.getAddress());
                        currentName = arg0.getAddress();
                        currentLng = arg0.getLocation().longitude;
                        currentLat = arg0.getLocation().latitude;
                        city = arg0.getAddressDetail().city;
                        province = arg0.getAddressDetail().province;
//                        intent.putExtra("lat",
//                            beans.get(arg2).location.latitude);
//                    intent.putExtra("lng",
//                            beans.get(arg2).location.longitude);
//                    intent.putExtra("name",
//                            beans.get(arg2).address);
////                    beans.get(arg2).city;
//                    intent.putExtra("city", beans.get(arg2).city);

//                    setResult(201,intent);
//                    MapActivity.this.finish();
                        //						System.out.println("arg=====size"+arg0.getPoiList().size());
                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                        System.out.println("adreess=================="+arg0.getAddress());
                        //						System.out.println("arg=====size"+arg0..size());
                    }
                });
            }

            @Override
            public void onMapStatusChange(MapStatus arg0) {
                // TODO Auto-generated method stub
                //				mPoiSearch
                //				.searchInBound(
                //						new PoiBoundSearchOption()
                //						.bound
                //						(arg0.bound).pageCapacity(30));
                //				mPoiSearch.searchNearby(arg0);
            }
        });
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        //		option.setLocationMode(LocationMode.Hight_Accuracy);
        option.setOpenGps(true);// 打开gps
        //		option.setPriority(LocationClientOption.GpsFirst);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(10000);
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener(){
        public void onGetPoiResult(PoiResult result){
            System.out.println("走了==================================================================="+result);
            if (result == null ) {
                System.out.println("空了==========");
                return;
                //未找到相关结果
            }else{
                if(result.getAllPoi()==null){
                    return;
                }
                System.out.println("没空 ");
                beans =result.getAllPoi();
                //				allSuggestions = result.getAllPoi();
                //				dialog.dismiss();
                //				lv.setAdapter(new lvadapter(POIActivity.this,allSuggestions));
                lv.setAdapter(new lvAdapter(result.getAllPoi()));
            }
            //获取POI检索结果
        }
        public void onGetPoiDetailResult(PoiDetailResult result){
            //获取Place详情页检索结果
        }
    };


    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            if(location.getLatitude()==4.9e-324){
                Toast.makeText(MapActivity.this, "定位失败", 0).show();
                return ;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            System.out.println("location=============="+location.getLatitude()+location.getLongitude());
            if (isFirstLoc) {

                currentName = location.getAddress().address;
                currentLng = location.getLongitude();
                currentLat = location.getLatitude();
                city = location.getCity();
                province = location.getProvince();

                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 17);
                mBaiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    class lvAdapter extends BaseAdapter {

        private List<PoiInfo> beans;

        public lvAdapter(List<PoiInfo> allPoi) {
            this.beans=allPoi;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 10;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return beans.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            arg1 = View.inflate(MapActivity.this, R.layout.lv_map, null);
            TextView tv= (TextView)arg1.findViewById(R.id.tv);
            TextView tv2= (TextView)arg1.findViewById(R.id.tv2);
            if(arg0<beans.size()){

                tv.setText(beans.get(arg0).name);
                tv2.setText(beans.get(arg0).address);
            }
            return arg1;
        }

    }
    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
//    private ListView lv;
//    private EditText et;
//    private LocationClient mLocationClient;
//    private MyLocationListener myListener;
//    private PoiSearch mPoiSearch;
//    private MapView map;
//    private BaiduMap baidu;
//    private boolean isfirst;
//    private List<PoiInfo> result;
//    private GeoCoder mSearch;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_map);
//        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
//        myListener = new MyLocationListener();
//        mLocationClient.registerLocationListener(myListener);    //注册监听函数
//        init();
//        et.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//                if (TextUtils.isEmpty(et.getText().toString())) {
//                    map.setVisibility(View.VISIBLE);
//                } else {
//
//                    map.setVisibility(View.GONE);
//                    mPoiSearch.searchInCity((new PoiCitySearchOption())
//                            .city("长春")
//                            .keyword(et.getText().toString())
//                            .pageCapacity(30));
////                    mSearch.searchInCity(new PoiCitySearchOption()
////                            .city("长春")
////                            .keyword(et.getText().toString())
////                            .pageNum(10));
//                }
//            }
//        });
//
//        mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
//            @Override
//            public void onGetPoiResult(PoiResult poiResult) {
//                Log.e("poiResult", poiResult.toString());
//                result =poiResult.getAllPoi();
//                if(result!=null){
//
//                    lv.setAdapter(new LvAdapter(result));
//                }
//            }
//
//            @Override
//            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
//                Log.e("poiResult", poiDetailResult.toString());
//            }
//        });
//
//    }
//    private void initLocation(){
//        LocationClientOption option = new LocationClientOption();
//        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
//        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
//        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
//        int span=10000;
//        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
//        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
//        option.setOpenGps(true);//可选，默认false,设置是否使用gps
//        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
//        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
//        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
//        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
//        mLocationClient.setLocOption(option);
//        mLocationClient.start();
//    }
//    private void init() {
//        lv = (ListView) findViewById(R.id.lv);
//        et = (EditText) findViewById(R.id.et);
//        map = (MapView)findViewById(R.id.baiduMap);
//        mPoiSearch = PoiSearch.newInstance();
//        mSearch = GeoCoder.newInstance();
//        baidu = map.getMap();
//        baidu.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
//            @Override
//            public void onMapStatusChangeStart(MapStatus mapStatus) {
//
//            }
//
//            @Override
//            public void onMapStatusChange(MapStatus mapStatus) {
//
//            }
//
//            @Override
//            public void onMapStatusChangeFinish(MapStatus mapStatus) {
////                sermapStatus.target
//                Log.e("", "搜索了");
//                LatLng la = new LatLng(mapStatus.target.latitude, mapStatus.target.longitude);
//                mPoiSearch.searchNearby(new PoiNearbySearchOption().location(la).keyword("小区").radius(5000).pageNum(10));
//            }
//        });
//        initLocation();
//    }
//
//    public class MyLocationListener implements BDLocationListener {
//
//        @Override
//        public void onReceiveLocation(BDLocation location) {
//
//            if(!isfirst){
//                map.getMap().animateMapStatus(MapStatusUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
//                isfirst=true;
//            }
//            //Receive Location
////            StringBuffer sb = new StringBuffer(256);
////            sb.append("time : ");
////            sb.append(location.getTime());
////            sb.append("\nerror code : ");
////            sb.append(location.getLocType());
////            sb.append("\nlatitude : ");
////            sb.append(location.getLatitude());
////            sb.append("\nlontitude : ");
////            sb.append(location.getLongitude());
////            sb.append("\nradius : ");
////            sb.append(location.getRadius());
////            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
////                sb.append("\nspeed : ");
////                sb.append(location.getSpeed());// 单位：公里每小时
////                sb.append("\nsatellite : ");
////                sb.append(location.getSatelliteNumber());
////                sb.append("\nheight : ");
////                sb.append(location.getAltitude());// 单位：米
////                sb.append("\ndirection : ");
////                sb.append(location.getDirection());// 单位度
////                sb.append("\naddr : ");
////                sb.append(location.getAddrStr());
////                sb.append("\ndescribe : ");
////                sb.append("gps定位成功");
////
////            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
////                sb.append("\naddr : ");
////                sb.append(location.getAddrStr());
////                //运营商信息
////                sb.append("\noperationers : ");
////                sb.append(location.getOperators());
////                sb.append("\ndescribe : ");
////                sb.append("网络定位成功");
////            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
////                sb.append("\ndescribe : ");
////                sb.append("离线定位成功，离线定位结果也是有效的");
////            } else if (location.getLocType() == BDLocation.TypeServerError) {
////                sb.append("\ndescribe : ");
////                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
////            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
////                sb.append("\ndescribe : ");
////                sb.append("网络不同导致定位失败，请检查网络是否通畅");
////            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
////                sb.append("\ndescribe : ");
////                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
////            }
////            sb.append("\nlocationdescribe : ");
////            sb.append(location.getLocationDescribe());// 位置语义化信息
////            List<Poi> list = location.getPoiList();// POI数据
////            if (list != null) {
////                sb.append("\npoilist size = : ");
////                sb.append(list.size());
////                for (Poi p : list) {
////                    sb.append("\npoi= : ");
////                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
////                }
////            }
////            Log.i("BaiduLocationApiDem", sb.toString());
//        }
//    }
//
//
//    class LvAdapter extends BaseAdapter{
//        private final List<PoiInfo> b;
//
//        public LvAdapter(List<PoiInfo> b) {
//            this.b = b;
//        }
//
//        @Override
//        public int getCount() {
//            return b.size();
//        }
//
//        @Override
//        public Object getItem(int i) {
//            return b.get(i);
//        }
//
//        @Override
//        public long getItemId(int i) {
//            return 0;
//        }
//
//        @Override
//        public View getView(int i, View view, ViewGroup viewGroup) {
//            view = View.inflate(MapActivity.this,R.layout.lv_map,null);
//            TextView tv1 = (TextView) view.findViewById(R.id.tvl1);
//            TextView tv2 = (TextView) view.findViewById(R.id.tvl2);
//
//            tv1.setText(b.get(i).name);
//            tv2.setText(b.get(i).address);
//            return view;
//        }
//    }
}
